package com.xinlong.service.impl;
import java.util.List;
import com.xinlong.dao.IUserDao;
import com.xinlong.entity.Permission;
import com.xinlong.entity.Role;
import com.xinlong.entity.Userinfo;
import com.xinlong.service.IuserService;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service("userService")
@Transactional
public class UserServiceimpl implements IuserService {

    @Autowired
    IUserDao iUserDao;

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Userinfo userinfo=iUserDao.findbyname(username);
        System.out.println(userinfo);
        User user=new User(userinfo.getUsername(),userinfo.getPassword(),userinfo.getStatus()==0?false:true,true,true,true, getAuthority(userinfo.getRoles()));
        return user;
    }


    private List<SimpleGrantedAuthority> getAuthority(List<Role> roles) {
        List<SimpleGrantedAuthority> authoritys = new ArrayList();
        for (Role role : roles) {
            authoritys.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleName()));
        }
        return authoritys;
    }

    public Userinfo findbyname(String name) {
        return iUserDao.findbyname(name);
    }

    public List<Userinfo> SelectUser() {
        return iUserDao.Selectuser();
    }

    //密码加密方法
    private static BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
    public static String encodePassword(String password){
        return bCryptPasswordEncoder.encode(password);
    }


    public void save(Userinfo userinfo) {
        userinfo.setPassword(encodePassword(userinfo.getPassword()));
        iUserDao.save(userinfo);
    }

    public Userinfo findbyid(String id) {
        return iUserDao.findbyid(id);
    }

    public List<Role> notUserbyRoleid(String id) {
        return iUserDao.notUserbyRoleid(id);
    }

    public void addRoleToUser(String userid, String[] roleids) {

        for (String roleid:roleids){
            iUserDao.addRoleToUser(userid,roleid);
        }
    }
}
